import React, { useEffect, useState } from "react";
import { cateColumn } from "./column";
import { Table, Input, Button, Popconfirm, message } from "antd";
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { queryAllCategory, deleteCate, deleteCates } from "@/api/cate.js";
import Catedialog from "./Cate/cateDialog";
import cateStyle from "./tag.module.scss";

export default function Category() {
  console.log("渲染")
  const [messageApi, contextHolder] = message.useMessage();
  const [search, setSearch] = useState("");
  const [id, setId] = useState(-1);
  const [type, setType] = useState(1);
  const [visible, setVisible] = useState(false);
  const [cateData, setCateData] = useState({});
  const [loading,setLoading] = useState(false);
  const [selectedRowKeys, SetselectedRowKeys] = useState();
  useEffect(() => {
    getList();
  }, []);

  // 实现v-model的效果
  const handleSearch = (e) => {
    setSearch(e.target.value);
  };

  // 请求列表
  const getList = async (params={page:1,size:10}) => {
    setLoading(pre=>!pre);
    if (!search) {
      const res = await queryAllCategory(params);
      console.log("taglist", res);
      setCateData(res.data);
    } else {
      const res = await queryAllCategory({ typeName: search,...params });
      console.log("taglist", res);
      setCateData(res.data);
    }
    setLoading(pre=>!pre);
  };
  // 控制对话框
  const changeVisible = (type, id) => {
    if (id) {
      setId(id);
    } else {
      setId(-1);
    }
    setVisible((pre) => !pre);
    changeType(type);
  };
  const deleteConfirm = async (id) => {
    console.log("confirm");
    try {
      const res = await deleteCate({ id });
      console.log(res, "deltesssss");
      if (res.code === 200) {
        messageApi.open({
          type: "success",
          content: "删除成功！",
          duration: 2,
        });
        getList();
      } else {
        messageApi.error("删除失败");
      }
    } catch (error) {
      messageApi.error("删除失败");
    }
  };
  const handleDeleteSelectConfirm = async () => {
    const ids = selectedRowKeys.join(",");
    console.log(ids, "--ids");
    try {
      const res = await deleteCates({ ids });
      console.log(res, "deltesssss");
      if (res.code === 200) {
        messageApi.open({
          type: "success",
          content: "删除成功！",
        });
        getList();
      } else {
        messageApi.error("删除失败");
      }
    } catch (error) {
      messageApi.error("删除失败");
    }
  };

  // 修改对话框类型
  const changeType = (type) => {
    setType(type);
  };
  const onSelectChange = (newSelectedRowKeys, selectedRow) => {
    SetselectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const handlePageOrSizeChange = (page,size)=>{
    getList({page,size})
  }

  // 表格的columns
  const columns = cateColumn({ changeVisible, deleteConfirm });
  return (
    <div className={cateStyle.cate}>
      <div className={cateStyle.top}>
        {contextHolder}
        <div className={cateStyle.search}>
          <h3>分类名称</h3>
          <Input
            placeholder="请输入分类名称"
            style={{ width: "200px", marginRight: "10px" }}
            value={search}
            onChange={handleSearch}
          />
          <Button
            icon={<SearchOutlined />}
            type="primary"
            className={cateStyle["ant-btn"]}
            onClick={()=>getList({page:cateData.currentPage,size:cateData.pageSize})}
          >
            查找
          </Button>
          <Button
            icon={<RedoOutlined />}
            className={cateStyle["ant-btn"]}
            onClick={() => setSearch("")}
          >
            重置
          </Button>
        </div>
        <div className={cateStyle.action}>
          <Button
            icon={<PlusOutlined />}
            className={cateStyle["ant-btn"]}
            type="primary"
            onClick={() => changeVisible(2)}
          >
            添加
          </Button>

          <Popconfirm
            title="提示"
            description="确定删除选中的标签吗?"
            cancelText="取消"
            okText="确认"
            onConfirm={handleDeleteSelectConfirm}
          >
            <Button
              icon={<DeleteOutlined />}
              danger
              type="primary"
              className={cateStyle["ant-btn"]}
              disabled={selectedRowKeys&&selectedRowKeys.length>0?false:true}
            >
              删除
            </Button>
          </Popconfirm>
        </div>
      </div>
      <Catedialog
        isOpen={visible}
        onChange={changeVisible}
        type={type}
        id={id}
        getList={getList}
      />
      <div className={cateStyle["table-container"]}>
        <Table
          columns={columns}
          dataSource={cateData.cateList}
          rowSelection={rowSelection}
          rowKey={(record) => record.id}
          sticky
          scroll={{ x: "auto" }}
          loading={loading}
          pagination={{
            pageSize: cateData.pageSize,
            current: cateData.currentPage,
            pageSizeOptions: [3, 5, 10, 20],
            showSizeChanger: true,
            total: cateData.total,
            showTotal: (total) => `共${total}条`,
            onChange: handlePageOrSizeChange,
            onShowSizeChange: handlePageOrSizeChange,
          }}
        />
      </div>
    </div>
  );
}
